<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="公告标题" prop="announcementTitle">
        <el-input
          v-model="queryParams.announcementTitle"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="公告类型" prop="announcementType">
        <el-select
          v-model="queryParams.announcementType"
          placeholder="请选择公告类型"
          clearable
          class="!w-240px"
        >
          <el-option label="通知公告" value="notice" />
          <el-option label="成绩公示" value="score" />
          <el-option label="证书公示" value="certificate" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="publishStatus">
        <el-select
          v-model="queryParams.publishStatus"
          placeholder="请选择发布状态"
          clearable
          class="!w-240px"
        >
          <el-option label="草稿" :value="0" />
          <el-option label="已发布" :value="1" />
          <el-option label="已撤回" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择关联计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:announcement:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:announcement:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="公告标题" align="center" prop="announcementTitle" width="200" />
      <el-table-column label="公告类型" align="center" prop="announcementType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_ANNOUNCEMENT_TYPE" :value="scope.row.announcementType" />
        </template>
      </el-table-column>
      <el-table-column label="关联计划" align="center" prop="planName" width="150" />
      <el-table-column label="发布人" align="center" prop="publisherName" width="100" />
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template #default="scope">
          {{ scope.row.publishTime ? formatDateTime(scope.row.publishTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" width="180">
        <template #default="scope">
          <span v-if="scope.row.validStartTime && scope.row.validEndTime">
            {{ formatDate(scope.row.validStartTime) }} ~ {{ formatDate(scope.row.validEndTime) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="浏览次数" align="center" prop="viewCount" width="80" />
      <el-table-column label="发布状态" align="center" prop="publishStatus" width="100">
        <template #default="scope">
          <el-tag :type="getPublishStatusTagType(scope.row.publishStatus)">
            {{ getPublishStatusText(scope.row.publishStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="isTop" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isTop ? 'success' : 'info'">
            {{ scope.row.isTop ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:announcement:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:announcement:update']"
            v-if="scope.row.publishStatus === 0"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="publish" v-if="scope.row.publishStatus === 0">
                  发布
                </el-dropdown-item>
                <el-dropdown-item command="withdraw" v-if="scope.row.publishStatus === 1">
                  撤回
                </el-dropdown-item>
                <el-dropdown-item command="top" v-if="!scope.row.isTop && scope.row.publishStatus === 1">
                  置顶
                </el-dropdown-item>
                <el-dropdown-item command="cancelTop" v-if="scope.row.isTop">
                  取消置顶
                </el-dropdown-item>
                <el-dropdown-item command="preview">
                  预览
                </el-dropdown-item>
                <el-dropdown-item command="delete" v-if="scope.row.publishStatus !== 1">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AnnouncementForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <AnnouncementDetail ref="detailRef" />
  
  <!-- 预览弹窗 -->
  <AnnouncementPreview ref="previewRef" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDate, formatDateTime } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalAnnouncementVO, 
  EvalAnnouncementPageReqVO, 
  getAnnouncementPage, 
  deleteAnnouncement, 
  exportAnnouncement,
  publishAnnouncement,
  withdrawAnnouncement,
  topAnnouncement,
  cancelTopAnnouncement
} from '@/api/eval/announcement'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import AnnouncementForm from './AnnouncementForm.vue'
import AnnouncementDetail from './AnnouncementDetail.vue'
import AnnouncementPreview from './AnnouncementPreview.vue'

/** 公告发布 列表 */
defineOptions({ name: 'EvalAnnouncement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalAnnouncementVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive<EvalAnnouncementPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  announcementTitle: undefined,
  announcementType: undefined,
  publishStatus: undefined,
  planId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const planList = ref<EvalPlanVO[]>([]) // 计划列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getAnnouncementPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 预览操作 */
const previewRef = ref()
const openPreview = (id: number) => {
  previewRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalAnnouncementVO) => {
  switch (command) {
    case 'publish':
      await handlePublish(row.id!)
      break
    case 'withdraw':
      await handleWithdraw(row.id!)
      break
    case 'top':
      await handleTop(row.id!)
      break
    case 'cancelTop':
      await handleCancelTop(row.id!)
      break
    case 'preview':
      openPreview(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 发布公告 */
const handlePublish = async (id: number) => {
  try {
    await message.confirm('确认发布该公告？')
    await publishAnnouncement(id)
    message.success('发布成功')
    await getList()
  } catch {}
}

/** 撤回公告 */
const handleWithdraw = async (id: number) => {
  try {
    await message.confirm('确认撤回该公告？')
    await withdrawAnnouncement(id)
    message.success('撤回成功')
    await getList()
  } catch {}
}

/** 置顶公告 */
const handleTop = async (id: number) => {
  try {
    await topAnnouncement(id)
    message.success('置顶成功')
    await getList()
  } catch {}
}

/** 取消置顶 */
const handleCancelTop = async (id: number) => {
  try {
    await cancelTopAnnouncement(id)
    message.success('取消置顶成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteAnnouncement(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportAnnouncement(queryParams)
    download.excel(data, '公告发布.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取发布状态标签类型 */
const getPublishStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
  return typeMap[status] || ''
}

/** 获取发布状态文本 */
const getPublishStatusText = (status: number) => {
  const textMap = { 0: '草稿', 1: '已发布', 2: '已撤回' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取所有状态的计划
    const allPlans = await Promise.all([
      getPlanListByStatus(2), // 已审批
      getPlanListByStatus(3), // 已发布
      getPlanListByStatus(4), // 进行中
      getPlanListByStatus(5)  // 已完成
    ])
    planList.value = allPlans.flat()
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
})
</script>
